# coding:utf-8
import datetime


class SerializrAbleMixin(object):
    """A SQLAlchemy mixin class that can serialize itself as a JSON object"""

    # args 自定义序列化字段 is_except 序列化是否排除字段  is_hump 返回是否用驼峰命名
    def to_dict(self, *args, is_except=False, is_hump=False):
        """
        序列化
        :param args: 自定义序列化字段
        :param is_except: 序列化是否根据args排除字段
        :param is_hump: 返回是否用驼峰命名
        :return: dict
        """
        value = dict()
        for column in self.__table__.columns:
            attribute = getattr(self, column.name)
            if isinstance(attribute, datetime.datetime):
                attribute = str(attribute)
            if is_hump is True:
                column_name = self.__hump(column.name)
            else:
                column_name = column.name
            if not args:
                value[column_name] = attribute
            else:
                if is_except is False:
                    if column.name in args:
                        value[column_name] = attribute
                else:
                    if column.name not in args:
                        value[column_name] = attribute
        return value

    def from_dict(self, attributes):
        """Update the current instance base on attribute->value by *attributes*"""
        for attribute in attributes:
            setattr(self, attribute, attributes[attribute])
        return self

    def __hump(self, column_name):
        column_list = column_name.split('_')
        for key in range(len(column_list)):
            if key != 0:
                column_list[key] = column_list[key].capitalize()
        return ''.join(column_list)
